/**
 * 权限指令
 * 用于控制元素的显示和隐藏
 */

import { useUserStore } from '../stores/user'

/**
 * 权限指令
 * 使用方式：
 * v-permission="'user:create'" - 检查是否有user:create权限
 * v-permission.role="'ADMIN'" - 检查是否有ADMIN角色
 * v-permission.any="['user:create', 'user:edit']" - 检查是否有任一权限
 * v-permission.all="['user:create', 'user:edit']" - 检查是否有所有权限
 */
export const permission = {
  mounted(el, binding) {
    const userStore = useUserStore()
    
    // 获取指令值
    const { value, modifiers } = binding
    
    if (!value) {
      return
    }
    
    let hasAccess = false
    
    // 检查角色权限
    if (modifiers.role) {
      hasAccess = userStore.hasRole(value)
    }
    // 检查是否有任一权限
    else if (modifiers.any && Array.isArray(value)) {
      hasAccess = value.some(permission => userStore.hasPermission(permission))
    }
    // 检查是否有所有权限
    else if (modifiers.all && Array.isArray(value)) {
      hasAccess = value.every(permission => userStore.hasPermission(permission))
    }
    // 默认检查单个权限
    else {
      hasAccess = userStore.hasPermission(value)
    }
    
    // 如果没有权限，隐藏元素
    if (!hasAccess) {
      el.style.display = 'none'
    }
  },
  
  updated(el, binding) {
    const userStore = useUserStore()
    
    const { value, modifiers } = binding
    
    if (!value) {
      return
    }
    
    let hasAccess = false
    
    if (modifiers.role) {
      hasAccess = userStore.hasRole(value)
    } else if (modifiers.any && Array.isArray(value)) {
      hasAccess = value.some(permission => userStore.hasPermission(permission))
    } else if (modifiers.all && Array.isArray(value)) {
      hasAccess = value.every(permission => userStore.hasPermission(permission))
    } else {
      hasAccess = userStore.hasPermission(value)
    }
    
    if (hasAccess) {
      el.style.display = ''
    } else {
      el.style.display = 'none'
    }
  }
}

/**
 * 角色指令
 * 使用方式：v-role="'ADMIN'"
 */
export const role = {
  mounted(el, binding) {
    const userStore = useUserStore()
    const hasRole = userStore.hasRole(binding.value)
    
    if (!hasRole) {
      el.style.display = 'none'
    }
  },
  
  updated(el, binding) {
    const userStore = useUserStore()
    const hasRole = userStore.hasRole(binding.value)
    
    if (hasRole) {
      el.style.display = ''
    } else {
      el.style.display = 'none'
    }
  }
}

/**
 * 管理员指令
 * 使用方式：v-admin
 */
export const admin = {
  mounted(el) {
    const userStore = useUserStore()
    const isAdmin = userStore.hasRole('ADMIN') || userStore.hasRole('SUPER_ADMIN')
    
    if (!isAdmin) {
      el.style.display = 'none'
    }
  },
  
  updated(el) {
    const userStore = useUserStore()
    const isAdmin = userStore.hasRole('ADMIN') || userStore.hasRole('SUPER_ADMIN')
    
    if (isAdmin) {
      el.style.display = ''
    } else {
      el.style.display = 'none'
    }
  }
}
